from copy import copy
import UAI
import Math
import Debug

class EmptyObject:
    pass


def obsticleInBetweenPos(p1, p2):
    p1x, p1y = p1
    angle, distance = Math.getAngleAndDistanceOfTwoPoints(p1, p2)
    for i in range(0, Math.normalize(int(distance)), UAI.ai.mathprecision):
        dx, dy = Math.getPointOfAngleAndDistance(angle, i)
        x = p1x + dx
        y = p1y + dy
        for object in UAI.game.getNonMovableObjects():
            if object.rect.collidepoint(x, y):
                return True
    return False

def obsticleInBetween(rect, pos):
    angle, distance = Math.getAngleAndDistanceOfTwoPoints(rect.center, pos)
    testrect = copy(rect)
    for i in range(0, Math.normalize(int(distance)), UAI.ai.mathprecision):
        dx, dy = Math.getPointOfAngleAndDistance(angle, i)
        testrect.centerx = rect.centerx + dx
        testrect.centery = rect.centery + dy
        obstical = collisionWithNonMovableObject(testrect)
        if obstical:
            return obstical
    return False

def obsticleInBetweenRects(rect1, rect2):
    angle, distance = Math.getAngleAndDistanceOfTwoPoints(rect1.center, rect2.center)
    if rect1.centerx > rect2.centerx:
        if rect1.centery > rect2.centery:
            if obsticleInBetweenPos(rect1.topright,   rect2.topright  ) and \
               obsticleInBetweenPos(rect1.bottomleft, rect2.bottomleft):
                return True
        else:
            if obsticleInBetweenPos(rect1.topleft    , rect2.topleft    ) and \
               obsticleInBetweenPos(rect1.bottomright, rect2.bottomright):
                return True
    else:
        if rect1.centery > rect2.centery:
            if obsticleInBetweenPos(rect1.topleft    , rect2.topleft    ) and \
               obsticleInBetweenPos(rect1.bottomright, rect2.bottomright):
                return True
        else:
            if obsticleInBetweenPos(rect1.topright,   rect2.topright  ) and \
               obsticleInBetweenPos(rect1.bottomleft, rect2.bottomleft):
                return True
    return False
    

def collisionWithNonMovableObject(rect):
        stationary = UAI.game.getNonMovableObjects()
        i = rect.collidelist(stationary)
        if i == -1:
            return False
        else:
            return stationary[i]


def loadImage(name, alpha=True):
    fullname = os.path.join('data', 'images', name + '.png')
    
    try:
        image = pygame.image.load(fullname)
    except pygame.error, message:
        print 'Cannot load image:', name
        raise SystemExit, message
    
    image = image.convert()
    
    if alpha == True:
        image.set_colorkey((255, 0, 255), pygame.RLEACCEL)
    
    return image, image.get_rect()